﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Milan
{
	public static class ZLib
	{
		/// <summary>
		/// Load a file and compress it into 
		/// </summary>
		/// <param name="fileName"></param>
		/// <returns>Returns array</returns>
		public static Byte[] LoadFileAndCompress( string fileName )
		{
			System.IO.MemoryStream outMemoryStream = new System.IO.MemoryStream();
			ComponentAce.Compression.Libs.zlib.ZOutputStream outZStream = new ComponentAce.Compression.Libs.zlib.ZOutputStream(outMemoryStream, ComponentAce.Compression.Libs.zlib.zlibConst.Z_DEFAULT_COMPRESSION);
			System.IO.FileStream inFileStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
			try
			{
				CopyStream(inFileStream, outZStream);
			}
			finally
			{
				outZStream.Close();
				outMemoryStream.Close();
				inFileStream.Close();
			}
			return outMemoryStream.ToArray();
		}

		/// <summary>
		/// Decompress one file to another.
		/// </summary>
		/// <param name="inFile"></param>
		/// <param name="outFile"></param>
		public static void DecompressFile(string inFile, string outFile)
		{
			System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);
			ComponentAce.Compression.Libs.zlib.ZOutputStream outZStream = new ComponentAce.Compression.Libs.zlib.ZOutputStream(outFileStream);
			System.IO.FileStream inFileStream = new System.IO.FileStream(inFile, System.IO.FileMode.Open);
			try
			{
				CopyStream(inFileStream, outZStream);
			}
			finally
			{
				outZStream.Close();
				outFileStream.Close();
				inFileStream.Close();
			}
		}


		public static void CopyStream(System.IO.Stream input, System.IO.Stream output)
		{
			byte[] buffer = new byte[2000];
			int len;
			while ((len = input.Read(buffer, 0, 2000)) > 0)
			{
				output.Write(buffer, 0, len);
			}
			output.Flush();
		}

	}
}
